package cn.wolfcode.shop.service.impl;

import java.util.Date;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.alibaba.dubbo.config.annotation.Service;

import cn.wolfcode.shop.domain.UserInfo;
import cn.wolfcode.shop.domain.UserLogin;
import cn.wolfcode.shop.exception.CodeMsg;
import cn.wolfcode.shop.exception.GlobalException;
import cn.wolfcode.shop.mapper.UserInfoMapper;
import cn.wolfcode.shop.mapper.UserLoginMapper;
import cn.wolfcode.shop.service.IUserService;
import cn.wolfcode.shop.util.MD5;
import cn.wolfcode.shop.util.RedisConstance;

@Service
@Transactional
public class UserServiceImpl implements IUserService {

	@Autowired
	private UserLoginMapper loginMapper;
	@Autowired
	private UserInfoMapper userInfoMapper;
	@Autowired
	private RedisTemplate redisTemplate;

	@Override
	public void register(String username, String password) {
		// 1.判断是否已经被注册
		// 2.如果已被注册,就抛出"用户已被注册异常"
		if (exists(username)) {
			throw new GlobalException(CodeMsg.USER_NAME_EXISTS);
		} else {
			// 否则在userlogin和userinfo新增数据
			UserLogin userLogin = new UserLogin();
			userLogin.setState(new Byte("0"));
			userLogin.setUserName(username);
			userLogin.setPassword(MD5.encode(password));
			loginMapper.insert(userLogin);
			UserInfo userInfo = new UserInfo();
			userInfo.setId(userLogin.getId());
			userInfo.setRegistTime(new Date());
			userInfoMapper.insert(userInfo);
		}
	}

	/**
	 * 判断是否被注册
	 * true代表注册过
	 * @param username
	 * @return
	 */
	private boolean exists(String username) {
		return loginMapper.exists(username) != null;
	}

	@Override
	public String login(String username, String password) {
		// 判断如果用户名密码非法,则抛出异常,用户名或密码有误
		if (!(StringUtils.hasLength(username) || StringUtils.hasLength(password))) {
			throw new GlobalException(CodeMsg.USER_NAME_OR_PASSWORD_ERROR);
		} else {
			// 否则去数据库查询对应的对象
			UserLogin userLogin = loginMapper.login(username, MD5.encode(password));
			//  如果用户为null,就会抛出异常
			if (userLogin == null) {
				throw new GlobalException(CodeMsg.USER_NAME_OR_PASSWORD_ERROR);
			}
			// 创建token,并且以token作为redis的key,userlogin作为redis的value
			String token = createToken(userLogin);
			return token;
		}
	}

	private String createToken(UserLogin userLogin) {
		String token = UUID.randomUUID().toString();
		// 存的是当前的登录用户,创建redis的时候可直接设置超时时间
		redisTemplate.opsForValue().set(RedisConstance.USER_CURRENT.replace("TOKEN", token), userLogin);
		//		redisTemplate.opsForValue().set(RedisConstance.USER_CURRENT.replace("TOKEN", token), userLogin, 10,
		//				TimeUnit.SECONDS);
		//		redisTemplate.expire(RedisConstance.USER_CURRENT.replace("TOKEN", token), 10, TimeUnit.SECONDS);
		return token;
	}

	@Override
	public void logout(String token) {
		if (!StringUtils.hasLength(token)) {
			throw new GlobalException(CodeMsg.USER_TOKEN_ERROR);
		}
//		UserLogin userLogin = (UserLogin) redisTemplate.opsForValue()
//				.get(RedisConstance.USER_CURRENT.replace("TOKEN", token));
//		if (userLogin == null) {
//			throw new GlobalException(CodeMsg.USER_TOKEN_ERROR);
//
//		}
		redisTemplate.delete(RedisConstance.USER_CURRENT.replace("TOKEN", token));
	}
	

    @Override
    public UserInfo getById(Long id) {
        return userInfoMapper.selectByPrimaryKey(id);
    }

}
